package com.enterprise.support.filter;

import com.enterprise.support.servlet.IServlet;
import com.enterprise.support.utility.*;
import com.enterprise.support.utility.console.ConsoleAction;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:14
 * Email: z82422@gmail.com
 * 初始化 Initial 接口，
 * 初始化 com.enterprise.support.utility.ActionContext
 */

public class ServletActionContextFilter implements Filter {

    static {
        PropertyConfigurator.configure(ServletActionContextFilter.class.getResource("/config/log4j.properties"));
    }

    private Logger logger = Logger.getLogger(ServletActionContextFilter.class);
    private ServletContext context = null;
    private String characterEncoding = null;
    private String excludeUrlPattern = null;
    private Enterprise h2Config = new Enterprise(Configuration.getProperties("/config/h2/config.properties"));
    private Enterprise servletConfig = new Enterprise(Configuration.getProperties("/config/web/servlet.properties"));
    private Enterprise<String, Class> servletClassConfig = new Enterprise();

    public void init(FilterConfig config) throws ServletException {
        try {
            context = config.getServletContext();
            characterEncoding = Validation.isEmpty(config.getInitParameter("characterEncoding")) ? "UTF-8" : config.getInitParameter("characterEncoding");
            excludeUrlPattern = Validation.isEmpty(config.getInitParameter("exclude-url-pattern")) ? null : config.getInitParameter("exclude-url-pattern");
            /*初始化扩展类*/
            String initclass = config.getInitParameter("initclass");
            if (Validation.isNotEmpty(initclass)) {
                Object initObject = Class.forName(initclass).newInstance();
                if (initObject instanceof Initial) {
                    ((Initial) initObject).init(context);
                }
            }

            /*加载 Simple Servlet 配置信息
            for (Map.Entry entity : simpleServletMappings.entrySet()) {
            }*/

            /*启动h2数据库*/
            if (h2Config.equals("starth2server", "true") && !H2ServerManager.isRun) {
                H2ServerManager.startServer();
            }

            /*修改保存路径*/
            if (!Configuration.get().isEmpty("web_fileuploader_directory")
                    && Configuration.get().equals("web_fileuploader_absolute", "false")) {
                Configuration.get().set("web_fileuploader_tempdirectory", new File(context.getRealPath("/static/fileuploader/temp")).getAbsolutePath());
                Configuration.get().set("web_fileuploader_directory", new File(context.getRealPath("/static/fileuploader")).getAbsolutePath());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final HttpSession session = request.getSession();
        final String contextPath = request.getContextPath();
        final String url = request.getRequestURI().substring(contextPath.length());
        if (!Validation.isEmpty(excludeUrlPattern) && url.matches(excludeUrlPattern)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            /*耗时,记录*/
            final long applicationTime = System.currentTimeMillis();

            /*设置请求编码格式*/
            request.setCharacterEncoding(characterEncoding);

            //init ActionContext:
            ActionContext.setContext(request, response, session, context);
            final Enterprise input = WebUtility.getInput(request);
            request.setAttribute("input", input);

            if (url.matches(".*enterprise_console_" + DataFormat.DateFormtString("yyyy_MM_dd", new Date()))) {
                /*输出 控制界面*/
                ConsoleAction console = new ConsoleAction();
                console.proccess();
            } else if (url.matches(".*enterprise_debug_" + DataFormat.DateFormtString("yyyy_MM_dd", new Date()))) {
                /*输出 系统信息，环境变量*/
                response.setContentType("text/html;charset=UTF-8");
                Enterprise cookies = WebUtility.getCookies();
                response.getWriter().println(input);
                response.getWriter().println(cookies);
            } else if (servletConfig.containsKey(url)) {
                /*Servlet配置*/
                IServlet servlet = null;
                try {
                    if (!servletClassConfig.containsKey(url)) {
                        servletClassConfig.put(url, Class.forName(servletConfig.getString(url)));
                    }
                    servlet = (IServlet) servletClassConfig.get(url).newInstance();
                    servlet.execute(request, response);
                } catch (Exception ex) {
                    throw new IOException(ex);
                } finally {
                    servlet = null;
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
            ActionContext.remove();
            logger.info("请求耗时:" + request.getRequestURL() + "," + (System.currentTimeMillis() - applicationTime) + "MS");
        }
    }

    public void destroy() {
        //Stop H2 Server
        H2ServerManager.stopServer();
    }
}
